package com.ibm.iisp.common.web.filter;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClasspathResourceFilter implements Filter {
	Logger log = LoggerFactory.getLogger(getClass());
	private boolean cacheable = false;
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fchain)
		throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) resp;
		if (cacheable) {
			// response.setDateHeader("Last-Modified", ctime);
			// Expires:过时期限值
			// response.setDateHeader("Expires", ctime + 20000);
			// Cache-Control来控制页面的缓存与否,public:浏览器和缓存服务器都可以缓存页面信息；
			response.setHeader("Cache-Control", "max-age=3600");
			// Pragma:设置页面是否缓存，为Pragma则缓存，no-cache则不缓存
			response.setHeader("Pragma", "Pragma");
		}
		HttpServletRequest request = (HttpServletRequest) req;
		ServletOutputStream outputStream = response.getOutputStream();
		String servletPath = request.getRequestURI();
		String path = servletPath.substring(servletPath.indexOf("/", 2) + 1);
		int indexOf = path.indexOf("?");
		if (indexOf > 0) {
			path = path.substring(0, indexOf);
		} else {
			indexOf = path.indexOf("#");
			if (indexOf > 0) {
				path = path.substring(0, indexOf);
			}
		}
		indexOf = path.lastIndexOf("/") + 1;
		String fileName = path.substring(indexOf);
		if (fileName.indexOf(".") < 0) {
			fileName = "index.html";
			path = path.substring(0, indexOf);
			path += fileName;
		}
		log.trace("path:{}", path);

		BufferedInputStream bis = null;

		byte[] contents = new byte[1024];
		int byteRead = 0;
		try {
			bis = new BufferedInputStream(getInputStream(path));
			while ((byteRead = bis.read(contents)) != -1) {
				outputStream.write(contents, 0, byteRead);
			}
			outputStream.flush();
		} catch (FileNotFoundException e) {
			response.setStatus(404);
		} catch (IOException e) {
			log.error("Erro to write classpath resource: " + path, e);
		} finally {
			if (bis != null) {
				bis.close();
			}
		}

	}

	public InputStream getInputStream(String path) throws FileNotFoundException {
		InputStream is = this.getClass().getClassLoader().getResourceAsStream(path);
		if (is == null) {
			throw new FileNotFoundException(path + " cannot be opened because it does not exist");
		}
		return is;
	}

	@Override
	public void init(FilterConfig conf) throws ServletException {
		String envName = conf.getInitParameter("envName");
		cacheable = "UAT".equals(envName) || "PROD".equals(envName);
	}

}
